import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common';
import { map, catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

interface CustomResponse<T> {
  data: T | null;
  status: number;
  success: boolean;
  message: string;
  time: number;
}

@Injectable()
export class Response<T = any> implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<CustomResponse<T>> {
    return next.handle().pipe(
      map(response => {
        return {
          data: response.data || null,
          status: response.status || 200,
          success: true,
          message: response.message || '成功',
          time: new Date().getTime()
        };
      }),
      catchError(err => {
        console.error('Error Info:', err);
        return throwError(() => err);
      })
    );
  }
}
